
# 1 + 11 + 111 + 11111 + 111111
import random
import threading
import time
from typing import List

from python_mysql_dome import session, Users, Session


def number():
    m = ""
    n = ""
    for i in range(1, 6):
        n += "1"
        if i == 1:
            m += n
        else:
            m += " + " + n

    return m


import uvicorn
from fastapi import FastAPI, Form, Header, Request
from pydantic import BaseModel
from starlette.middleware.cors import CORSMiddleware


app = FastAPI()
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

@app.get("/")
async def root():
    return {"message": "Hello World"}

@app.get("/echo/{text}")    #注意这里text将是函数定义的参数名.
async def getEchoApiUrl(text:str):    #通过定义参数类型可以让fastapi进行默认的参数检查.
    return {"echo":text}

@app.get("/echo1")    #注意这里url上没有定义参数
async def getEchoApiParams(text:str, h:int, j:int):    #fastapi会聪明的发现它不是URL参数,然后自动将他识别为param参数.
    return {"echo":text, "h":h, "j":j}

# class Demo(BaseModel):
#     a: int # 整型
#     b: float # 浮点型
#     c: str # 字符串
#     d: bool # 布尔型
#     e: List[int] # 整型列表
#     f: Dict[str, int] # 字典型，key为str，value为int
#     g: Set[int] # 集合
#     h: Tuple[str, int] # 元组

class Agent(BaseModel):    #继承BaseModel
    id:str
    name:str
    address:str

class store(BaseModel):    #继承BaseModel
    id:str
    user:str
    address:str

class EchoArgs(BaseModel):    #继承BaseModel
    text:str
    name:str
    age:int
    agent:Agent
    stores:List[store]

def addUser(m, session):
    try:
        obj = Users(id = 14, name="thread", extra='牛逼', createdAt = time.localtime(), updatedAt = time.localtime())
        session.add(obj)
        session.commit()
    except:
        m["rollback"] = True

def updateUser(m, session):
    try:
        session.query(Users).filter(Users.id == 6).update({"extra": "boot async"})
        session.commit()
    except:
        m["rollback"] = True

def deleteUser(m, session):
    try:
        session.query(Users).filter(Users.id == 13).delete()
        session.commit()
    except:
        m["rollback"] = True

@app.post("/echo2")    #get不支持请求体,更换请求方法
async def postEchoApiBody(args:EchoArgs, token:str = Header(None)):    #设置刚才定义的参数

    m = {"rollback":False}
    session_list = []
    task_list = []

    session1 = Session()
    t1 = threading.Thread(target=addUser, args=(m, session1,))
    t1.start()
    session_list.append(session1)
    task_list.append(t1)

    session2 = Session()
    t2 = threading.Thread(target=updateUser, args=(m, session2,))
    t2.start()
    session_list.append(session2)
    task_list.append(t1)

    session3 = Session()
    t3 = threading.Thread(target=deleteUser, args=(m, session3,))
    t3.start()
    session_list.append(session3)
    task_list.append(t1)

    # for t in task_list:
    #     t.join()

    # if m["rollback"] == True:
    #     for s in session_list:
    #         session.rollback()
    # else:
    #     session.commit()

    users = session.query(Users).all()
    return {"echo":args, "token":token, "users":users}

@app.post("/echo3")
async def postEchoApiForm(text:str=Form(None), text1:int=Form(None), text2:float=Form(None)):    #通过Form设置参数
    return {"echo":text, "echo1":text1, "echo2":text2}    #原样返回

@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    print("start_time：", start_time)

    auth = request.headers.get("token", None)
    print("auth：", auth)
    response = await call_next(request)

    process_time = time.time() - start_time
    print("process_time：", process_time)

    response.headers["X-Process-Time"] = str(process_time)
    return response

def creat_phone():
    # 第二位
    second = [3, 4, 5, 7, 8][random.randint(0, 4)]

    # 第三位的值根据第二位来确定
    third = {
        3: random.randint(0, 9),
        4: [5, 7, 9][random.randint(0, 2)],
        5: [i for i in range(10) if i != 4][random.randint(0, 8)],
        7: [i for i in range(10) if i not in [4, 9]][random.randint(0, 7)],
        8: random.randint(0, 9)
    }[second]
    # 后8位随机抽取
    suffix = ''
    for x in range(8):
        suffix = suffix + str(random.randint(0, 9))
    # 拼接
    return "1{}{}{}".format(second, third, suffix)

if __name__ == '__main__':
    a = 1
    aTupl = (a, )
    print(aTupl)

    print(creat_phone())

    l = []
    if l is None:
        print("空")

    uvicorn.run(app='main:app', host="127.0.0.1", port=8000, reload=True, debug=True)

    # print(number())

